package org.neurone.action.session;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.neurone.action.BaseActionSupport;
import org.neurone.application.impl.UrlGenerator;
import org.neurone.context.MessageConst;
import org.neurone.context.SessionConst;
import org.neurone.session.SessionHive;
import org.neurone.session.SessionServer;
import org.neurone.session.impl.SessionHiveLocal;
import org.neurone.session.impl.SessionServerLocal;
import org.neurone.userspace.userinfo.UserMgr;
import org.neurone.userspace.verification.Verification;

public class SessionLoginAction extends BaseActionSupport{
	/**
	 * 
	 */
	private static final long serialVersionUID = -5744879731244583662L;

	private String userName;
	private String password;
	private String identifyingCode;
	private String fromURL;
	private String appKey;
	private String token;


	public String getUserName() {
		return userName;
	}

	public String getPassword() {
		return password;
	}

	public String getIdentifyingCode() {
		return identifyingCode;
	}


	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setIdentifyingCode(String identifyingCode) {
		this.identifyingCode = identifyingCode;
	}

	
	public String getFromURL() {
		return fromURL;
	}

	public void setFromURL(String fromURL) {
		this.fromURL = fromURL;
	}

	public String getAppKey() {
		return appKey;
	}

	public void setAppKey(String appKey) {
		this.appKey = appKey;
	}

	public String getToken() {
		return token;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public String login() {
		
		boolean userAvail = sessionHive.loginSession(this.userName, this.password);
		
		if ((! userAvail)||(sessionHive.checkSession() == null))
		{
			this.addActionError(MessageConst.LOGIN_FAILD);
			return LOGIN;
		}
		
		if(fromURL != null)
		{
			
			return success(UrlGenerator.generateURLByAppKey(this.appKey, this.fromURL));
		}
		else
		{
			return home();
		}
	}

	public String loginByToken()
	{
		
		this.sessionHive.loginByToken(this.token, this.appKey);
		
		if (sessionHive.checkSession() == null)
		{
			this.addActionMessage( MessageConst.LOGIN_FAILD);
		}
		
		return success("loginByTokenSuccess?appKey="+this.appKey+"&fromurl="+this.fromURL);
		
	}

	public String logout() {	
		this.sessionHive.logoutSession();
		
		return success("");
	}

	@Override
	public void validate() {
		String vc = (String)this.httpSession.getAttribute(SessionConst.SESSION_IDENTIFYING_CODE);
		if((vc != null)&&(! vc.equals(this.identifyingCode)))
		{
			this.addFieldError("identifyingCode", "验证码错误");
		}
	}
	
	
}
